#include <string.h>
#include <stdio.h>
#include "Time.h"

#include "Log.h"

#define LOGLINEMAXNUM 50000

LogManager::LogManager()
{
	m_pFile      = NULL;
	m_bToConsole = false;
	m_uLineNum   = 0;
	m_uBeginTime = 0;
	memset(m_szPreName, 0, PREFIXNAMELEN);
	memset(m_szPath,    0, LOGPATHSTRLEN);
	memset(m_szName,    0, LOGNAMESTRLEN);
}

LogManager::~LogManager()
{
	if ( m_pFile )	{
		fclose(m_pFile);
	}
}

bool LogManager::Init(const char* pPath, const char* pPreName, bool toConsole)
{
	if ( pPreName == NULL || pPath == NULL )
		return false;
	strncpy(m_szPath,    pPath,    LOGPATHSTRLEN);
	strncpy(m_szPreName, pPreName, PREFIXNAMELEN);
	m_bToConsole = toConsole;

	return NewLogFile();
}

bool LogManager::Update()
{
	if ( m_uLineNum >= LOGLINEMAXNUM || !IsSameDay(m_uBeginTime))
		if ( !NewLogFile() ) return false;
	return true;
}

bool LogManager::NewLogFile()
{
	if ( m_pFile )	{
		fclose(m_pFile);
		m_pFile = NULL;
	}
	m_uLineNum = 0;
	m_uBeginTime = GetTime();
	sprintf(m_szName,"%s%s.log", m_szPreName, GetStrTime(m_uBeginTime,"%m%d%H%M%S"));
	
	char buff[LOGPATHSTRLEN+LOGNAMESTRLEN] = "";
	sprintf(buff,"%s/%s", m_szPath, m_szName);
	m_pFile = fopen(buff, "w");
	if ( m_pFile == NULL )
		return false;
	return true;
}

bool LogManager::RecordInfoToFile( char* info )
{
	if ( !info )
		return false;
	if ( !LogManager::Update() )
		return false;
	size_t len = strlen(info);
	if ( len > LOGLINEBUFFLEN-2 )
		len = LOGLINEBUFFLEN-2;
	info[len] = '\n';
	info[len+1] = '\0';
	if ( m_bToConsole )
		printf("%s",info);
	if ( m_pFile )
		if ( EOF == fputs(info, m_pFile) ) 
			return false;
	m_uLineNum++;
	return true;
}

bool LogManager::CloseLog()
{
	if ( m_pFile )	{
		fclose(m_pFile);
		m_pFile = NULL;
	}
	memset(m_szName,    0, LOGNAMESTRLEN);
	memset(m_szPath,    0, LOGPATHSTRLEN);
	memset(m_szPreName, 0, PREFIXNAMELEN);
	m_uBeginTime = 0;
	m_uLineNum   = 0;
	m_bToConsole = false;
	return true;
}
